var link_temp = [];
toastr.options={closeButton:true,debug:false,progressBar:true,positionClass:"toast-top-right",onclick:null,showDuration:"300",hideDuration:"1000",timeOut:"2000",extendedTimeOut:"1000",preventDuplicates:true,showEasing:"swing",hideEasing:"linear",showMethod:"fadeIn",hideMethod:"fadeOut"};
$(document).ready(function(){
	// 初始化 导航
	
	
	var cur_node = $("#cur_node").val();
	if(cur_node !== ""){
		menu_click($("#tree_node_"+cur_node));
	}
});



function menu_click(ths){
	
	const pid = $(ths).attr("data-menu-pid");
	const requestUrl = $(ths).attr("data-href");
	const nowNodeId = $(ths).attr("id").replace("tree_node_","");
	const pageTitle = "主页-"+$(ths).attr("data-menu-name");
	
	$(".nav-link").removeClass("active");
	
	$(ths).addClass("active");
	
	nodeChangeActive(pid);
	
	
	var datas={
		"menuId":nowNodeId,
		"pageTitle":pageTitle,
		"requestUrl":requestUrl,
		"happenTime":new Date()
	};
	
	//$("head")[0].find("title").text(pageTitle);
	$(document).attr("title",pageTitle);
	
	window.history.pushState(datas,pageTitle,requestUrl);
	$("#breadcrumb_0").empty();
	initNavBreadcrumb($(ths));
	showPage(datas);
	
	
}

function initNavBreadcrumb(ths){
	$("#breadcrumb_0").prepend("<li class='breadcrumb-item active'>"+(ths.text())+"</li>");
	const pid = ths.attr("data-menu-pid");
	if(typeof(pid) !== "undefined" && pid != null && pid !== ""){
		initNavBreadcrumb($("#tree_node_"+pid));
	}
}

function nodeChangeActive(pid){
	if(typeof(pid) !== "undefined" && pid != null && pid !== ""){
		$("#tree_node_"+pid).addClass("active");
		nodeChangeActive($("#tree_node_"+pid).attr("data-menu-pid"));
	}
}

window.addEventListener("popstate", function() {
    // 取出 设置好的 history.state 值，做判断
	var state = history.state;
	menu_click($("#tree_node_"+state.menuId));

});


function showPage(datas){
	var time = datas.happenTime.format("yyyy-MM-dd hh:mm:ss");
	const requestData = "{'nowNodeId':"+(datas.menuId)+",'visitAddr':'"+(datas.requestUrl)+"','reportDate':'"+time+"'}";
	$('#content_wrapper').html(""); 
	try{
		$.ajax({
			url:"/report/node",
			type:"POST",
			contentType: "application/json",
			timeout:10000,
			async:true,
			cache:false,
			data:requestData,
			dataType:"json",
			success:function(data){
				if(data.code === 200){
					
					$.ajax({
						url:datas.requestUrl,
						type:"POST",
						timeout:10000,
						contentType:"application/json;charset=UTF-8",
						async:true,
						cache:false,
						dataType:"text",
						success:function(data){
							try{
								if(link_temp.length > 0 ){
									for(var j=0;j< link_temp.length; j++){
										$("#"+link_temp[j]).remove();
									}
								}
								
								link_temp = [];
								var parser = new DOMParser();
							    var xmlObject = parser.parseFromString(data, "text/html");
								var cssContent = xmlObject.getElementsByTagName("css_command");
								
								if(typeof(cssContent) !== "undefined" && cssContent != null && cssContent.length == 1){
									var links = cssContent[0].getElementsByTagName("link");
									loadPartCSS(links,0);
								}
								
								var bodyContent = xmlObject.getElementsByTagName("body_command")[0];
								if(typeof(bodyContent) !== "undefined" && bodyContent != null ){
									$('#content_wrapper').empty(); 
									$('#content_wrapper').append(bodyContent.innerHTML);
								}
								
								var scriptContent = xmlObject.getElementsByTagName("script_command");
								$('#script_wrapper').empty();
								if(typeof(scriptContent) !== "undefined" && scriptContent != null && scriptContent.length == 1){
									if(typeof(scriptContent[0].childNodes) !== 'undefined' && scriptContent[0].childNodes != null && scriptContent[0].childNodes.length > 0){
										var scripts = scriptContent[0].getElementsByTagName("script");
										loadPartJS(scripts,0);
									}
								}else{
									$('#script_wrapper').html("");
								}
							}catch(e){
								console.log(e);
							}
						},error:function(e){
							console.log(e);
						}
						
					});
					
				}
			},error:function(e){
				console.log(e);
			}
		});
	}catch(e){
		console.error(e);
	}
}

function loadPartCSS (links,i){
	var id = links[i].getAttribute("id");
	link_temp.push(id);
	var src = links[i].getAttribute("href") ;//+'?r='+ Math.random()
	var rel = links[i].getAttribute("rel");
    var script_dom = document.createElement('link');
    script_dom.href = src;
    script_dom.rel = rel;
    script_dom.id = id;
    var script_wrapper = document.getElementsByTagName('head').item(0);
    script_wrapper.appendChild(script_dom);
    script_dom.onload = script_dom.onreadystatechange= function(){
    	if (!this.readyState || 'loaded' === this.readyState || 'complete' === this.readyState) {
    		if(i < links.length -1){
    			loadPartCSS(links,i+1);
    		}
    	}
    }
}


function loadPartJS(scripts,i){
	var src = scripts[i].getAttribute("src") ;//+'?r='+ Math.random() 
    var script_dom = document.createElement('script');
    var id = scripts[i].getAttribute("id");
	link_temp.push(id);
    script_dom.src = src;
   
    script_dom.language = 'javascript';
    script_dom.type = 'text/javascript';
    script_dom.id=id;
    var script_wrapper = document.getElementById('script_wrapper');
    script_wrapper.appendChild(script_dom);
    script_dom.onload = script_dom.onreadystatechange= function(){
    	if (!this.readyState || 'loaded' === this.readyState || 'complete' === this.readyState) {
    		if(i < scripts.length -1){
    			loadPartJS(scripts,i+1);
    		}
    		
    	}
    }
}

/**
 *对Date的扩展，将 Date 转化为指定格式的String
 *月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
 *年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
 *例子：
 *(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
 *(new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
 */
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}